package com.yantong.pay.yfz.util;

import com.alibaba.fastjson.JSONObject;
import com.yantong.pay.yfz.domain.domain.Response;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;


public class HttpUtil {
	private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
    private static final CloseableHttpClient HTTPCLIENT = HttpClients.createDefault();
    private static void debug(String msg, Object... args) {
    	if("debug".equalsIgnoreCase(System.getProperty("sdk.mode"))) {
    		msg = String.format(msg, args);
    		System.out.println(msg);
    	}
    }
    /**
     * post请求（用于请求json格式的参数）
     * @param url
     * @param params
     * @return
     */
    public static <T extends Response> T post(String url, String params , Map<String , String> header , Class<T> clazz , String publicKeyFileUri) throws Exception {
    	final long start = System.currentTimeMillis();
    	debug("\n---------------------------------------------------------------");
    	debug("接口地址：%s", url);

        T responseResult = clazz.newInstance();
        CloseableHttpClient HTTPCLIENT = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        HttpPost httpPost = null;
        try {

	        httpPost = new HttpPost(url);// 创建httpPost
	        //httpPost.setHeader("Content-Type", "application/json");
	        for (String key : header.keySet()){
	            httpPost.setHeader(key , header.get(key));
	        }
	        logger.info("接口头参数(%d)：%s"+header);
	        String charSet = "UTF-8";
	        StringEntity entity = new StringEntity(params, charSet);
	        httpPost.setEntity(entity);
	        logger.info("接口报文(%d)：%s"+params);
	    	responseResult.setInputJSON(params.toString());

            response = HTTPCLIENT.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                //验签
                String jsonString = EntityUtils.toString(response.getEntity(), "UTF-8");
	            logger.info("响应消息(%d)：%s"+jsonString);
            	responseResult.setOutputJSON(jsonString);
            	if(response.getFirstHeader("x-efps-sign")==null || response.getFirstHeader("x-efps-sign-no")==null){
                    responseResult.setReturnCode("-1");
                    responseResult.setReturnMsg(jsonString);
                    return responseResult;
                }

                String signResult = response.getFirstHeader("x-efps-sign").getValue();
                String signNo = response.getFirstHeader("x-efps-sign-no").getValue();
	            logger.info("响应证书号：%s"+signNo);
	            logger.info("响应签名：%s"+signResult);
                if(signResult!=null && !"".equals(signResult) && verify(jsonString , signResult , Config.getPublicKeyFile(publicKeyFileUri))){
                    responseResult = JSONObject.parseObject(jsonString, clazz);
                }else{
                    responseResult.setReturnCode("-1");
                    responseResult.setReturnMsg("验签失败");
                }
            }else{
                responseResult.setReturnCode(String.valueOf(state));
                debug("请求返回："+state+"("+url+")");
            }
        }catch(Exception e) {
        	e.printStackTrace();
        } finally {
        	if(httpPost != null) {
        		httpPost.releaseConnection();
        	}
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if(responseResult != null) {
        	debug("接口返回码%s，详细：%s", responseResult.getReturnCode(), JSONObject.toJSONString(responseResult));
        } else {
        	debug("接口调用失败！");
        }
        return responseResult;
    }


    /**
     * 验签
     * @param content 原字符串
     * @param sign 已签名字符串
     * @return
     * @throws Exception
     */
    public static boolean verify(String content , String sign , InputStream inputStream) throws Exception  {

        boolean flag = false;
        if(content != null && !content.equals("") && sign != null && !sign.equals("")){

            boolean result = RsaUtils.vertify(RsaUtils.getPublicKey(inputStream), content , sign ) ;
            debug("验签结果:" + result);
            if(result){
                flag = true ;
            }
        }
        return flag;
    }

}
